<template>
  <v-container fluid>
    <v-row justify="center">
      <v-col sm="4" md="4" lg="3">
        <v-card>
          <v-img src="../assets/login/background.png" class="white--text align-center" alt="密码修改">
            <v-card-title>密码修改</v-card-title>
          </v-img>
          <v-form ref="passwordChangeForm" v-model="valid" lazy-validation>
            <v-card-text>
              <v-text-field v-model="password" :rules="passwordRules" label="密码" required :append-icon="show ? 'mdi-eye' : 'mdi-eye-off'" @click:append="show = !show" :type="show ? 'text': 'password'">
              </v-text-field>
              <v-text-field v-model="passwordConfirm" :rules="[passwordConfirmRules.required, passwordConfirmRules.equal(password, passwordConfirm)]" label="确认密码" required :append-icon="show ? 'mdi-eye' : 'mdi-eye-off'" @click:append="show = !show" :type="show ? 'text': 'password'">
              </v-text-field>
              <!--保存按钮-->
              <v-btn :disabled="!valid" color="primary" class="mr-4" v-on:click="validate">提交</v-btn>
            </v-card-text>
          </v-form>
        </v-card>
      </v-col>
    </v-row>
    <v-snackbar
      v-model="snackbar"
    >
      密码修改成功
      <template v-slot:action="{ attrs }">
        <v-btn
          color="pink"
          text
          v-bind="attrs"
          @click="snackbar = false"
        >
          Close
        </v-btn>
      </template>
    </v-snackbar>
  </v-container>
</template>

<script>
export default {
  name: 'PasswordChange',
  data: () => ({
    snackbar: false,
    valid: true,
    show: false,
    password: '',
    passwordRules: [
      v => !!v || '请输入密码',
      v => (v.length >= 6 && v.length <= 20) || '密码应当在6-20个字符以内'
    ],
    passwordConfirm: '',
    passwordConfirmRules: {
      required: v => !!v || '请输入确认密码',
      equal: (password, passwordConfirm) => (password === passwordConfirm) || '两次密码不一致'
    }
  }),
  methods: {
    validate () {
      const valid = this.$refs.passwordChangeForm.validate()
      if (valid) {
        this.$axios.post('rest_auth/password/change/', {
          new_password1: this.password,
          new_password2: this.passwordConfirm
        }).then(response => {
          console.log(response)
          this.snackbar = true
          // 密码修改后注销用户并跳转到登录界面
          this.$store.commit('removeToken')
          this.$router.push({
            name: 'Login'
          })
        }).catch(error => {
          console.log(error)
        })
      }
    }
  }
}
</script>

<style scoped>

</style>
